from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from ..core.database import get_db, get_db_context
from ..models.transaction import Transaction
from ..schemas.query import TransactionResponse

router = APIRouter()

@router.get("/transactions", response_model=List[TransactionResponse])
async def get_transactions(
    pan: Optional[str] = Query(None, description="卡号"),
    trans_code: Optional[str] = Query(None, description="交易类型（CEP/CEQ/CEF/FES）"),
    start_date: Optional[str] = Query(None, description="开始日期（YYYYMMDD）"),
    end_date: Optional[str] = Query(None, description="结束日期（YYYYMMDD）"),
    orderid: Optional[str] = Query(None, description="订单号"),
    trans_sn: Optional[str] = Query(None, description="交易流水号")
):
    """
    查询交易记录
    支持按卡号、交易类型、日期范围、订单号、流水号等条件筛选
    """
    try:
        with get_db_context() as db:
            query = db.query(Transaction)
            
            # 添加查询条件
            if pan:
                query = query.filter(Transaction.pan == pan)
            if trans_code:
                query = query.filter(Transaction.trans_code == trans_code)
            if orderid:
                query = query.filter(Transaction.orderid == orderid)
            if trans_sn:
                query = query.filter(Transaction.trans_sn == trans_sn)
            if start_date:
                query = query.filter(Transaction.trans_date >= start_date)
            if end_date:
                query = query.filter(Transaction.trans_date <= end_date)
            
            # 按创建时间倒序排序
            query = query.order_by(Transaction.created_at.desc())
            
            # 执行查询并返回
            transactions = query.all()
            return transactions
            
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"查询交易记录失败: {str(e)}"
        )

@router.get("/transactions/{trans_sn}", response_model=TransactionResponse)
async def get_transaction_by_sn(trans_sn: str):
    """
    根据交易流水号查询单笔交易
    """
    try:
        with get_db_context() as db:
            transaction = db.query(Transaction).filter(Transaction.trans_sn == trans_sn).first()
            if not transaction:
                raise HTTPException(status_code=404, detail="未找到该交易记录")
            return transaction
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"查询交易记录失败: {str(e)}"
        ) 